package com.example.forumsystem.interceptor;


import com.example.forumsystem.config.AppConfig;
import com.example.forumsystem.model.User;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;


@Configuration
public class LoginInterceptor implements HandlerInterceptor {
    //从配置⽂件中获取默认登录⻚的URL
    @Value("${forum.login.url}")
    public String defaultURL;
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        HttpSession session = request.getSession(false);
        if(session != null && session.getAttribute(AppConfig.USER_SESSION) != null) {
            // 已经登入
            return true;
        }
        // 没有登录强制跳转到登录⻚⾯
        if(!defaultURL.startsWith("/")) {
            defaultURL = "/" + defaultURL;
        }
        response.sendRedirect(defaultURL);
        return false;
    }
}
